package com.itboy.demo.controller;

import com.itboy.common.config.RuoYiConfig;
import com.itboy.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
@RestController
public class TestController {
	private static String separator = File.separator;




	/**
	 * 备份数据库
	 */
	@RequestMapping("/db")
	public AjaxResult<Void> list(HttpServletRequest request) {
		try {
			String realPath = RuoYiConfig.getProfile();
			String path = realPath + "/dbBackUp/" + separator;
			String sqlFileName = getRunTimeName();
			dbBackUp("root", "257257cao", "jdbc:mysql://rm-uf6375ff7v9ge2dzsoo.mysql.rds.aliyuncs.com:3306/itboy5?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai", path, sqlFileName);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("备份数据失败");
		}
		return AjaxResult.success("备份成功");
	}
	/**
	 *
	 * @param root 用户名
	 * @param pwd 密码
	 * @param dbName 数据库名
	 * @param backPath 保存路径
	 * @param backName 保存名称
	 * @throws Exception
	 */
	public static void dbBackUp(String root,String pwd,String dbName,String backPath,String backName) throws Exception {
		String pathSql = backPath+backName;
		File fileSql = new File(pathSql);
		File file = new File(backPath);
		//创建备份sql文件
		file.mkdirs();
		if (!fileSql.exists()){
			fileSql.createNewFile();
		}
		//mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
		StringBuffer sb = new StringBuffer();
		sb.append("mysqldump");
		sb.append(" -h 127.0.0.1");//此处ip可以是别的机器的ip
		sb.append(" -u"+root);
		sb.append(" -p"+pwd);
		sb.append(" "+dbName+" >");
		sb.append(pathSql);
		System.out.println("cmd命令为："+sb.toString());
		Runtime runtime = Runtime.getRuntime();
		System.out.println("开始备份："+dbName);
		System.out.println("cmd /c"+sb.toString());
		Process process = runtime.exec("cmd /c"+sb.toString());
		System.out.println("备份成功!");
	}
	public static String getRunTimeName() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String newDate=sdf.format(new Date());
		String result="";
		Random random=new Random();
		for(int i=0;i<3;i++){
			result+=random.nextInt(10);
		}
		return newDate+result+".sql";
	}
}
